package codingforgreat.lchot150;

import java.util.HashMap;
import java.util.HashSet;

public class Lc128 {    public int longestConsecutive(int[] nums) {
    HashMap<Integer,Integer> head = new HashMap<>();
    HashMap<Integer,Integer> tail = new HashMap<>();
    HashSet<Integer> visited = new HashSet<>();
    for(int num : nums){
        if(!visited.contains(num)){
            head.put(num,1);
            tail.put(num,1);
            visited.add(num);
            if(tail.containsKey(num - 1)){
                int preLen  = tail.get(num - 1);
                int preHead = num - preLen;
                head.put(preHead,preLen + 1);
                tail.put(num,preLen + 1);
                tail.remove(num - 1);
                head.remove(num);
            }
            if(head.containsKey(num + 1)){
                int preLen = tail.get(num);
                int preHead = num - preLen + 1;
                int postLen = head.get(num + 1);
                int postTail = num + postLen;
                head.put(preHead, preLen + postLen);
                tail.put(postTail, preLen + postLen);
                head.remove(num + 1);
                tail.remove(num);
            }
        }
    }
    int ans = 0;
    for(int len : head.values()){
        ans = Math.max(ans,len);
    }
    return ans;
}

}
